<template>
  <div class="search-bar">
      <!-- show search button in keybord -->
      <form action='' onsubmit="return false;">
        <mu-flexbox :gutter="0">
          <mu-flexbox-item grow="5">
            <input class="search-input mu-text-field-input"  v-focus="focusState" type="search" :placeholder="placeholder" v-model="inputValue" @search="handleSearch" ref="input1"/>
          </mu-flexbox-item>
          <mu-flexbox-item grow="1">
            <i class="iconfont icon-ssousuo" v-if="!inputValue" @click="handleSearch"></i>
            <i class="iconfont icon-close" @click="handleClose" v-else></i>
          </mu-flexbox-item>
        </mu-flexbox>
      </form>
  </div>
</template>

<script>
export default {
  name: 'search-bar',
  props: {
    placeholder: {
      type: String,
      default: '输入中文名称或拼音首字母查询'
    },
    defaultValue: '',
    focusState: {
      type: Boolean,
      default: true
    },
    dType: {
      type: Number,
      default: 1
    },
  },
  directives: {
    focus: {
      update: function (el, value) {
        if (value) {
          el.focus()
        }
      }
    }
  },
  watch: {
    defaultValue (v) {
      this.inputValue = v
    },
    inputValue (val) {
      if (val) {
        if (this.$route.path.indexOf('/about/price') != -1) {
          this.$emit('search', this.inputValue)
        }
      }
    }
  },
  data () {
    return {
      inputValue: '',
      timer: null
    }
  },
  methods: {
    goSearch () {
      if (this.$route.path.indexOf('/about/price') != -1) {
        return
      } else {
        this.$router.push(`/about/search?dType=${this.dType}`)
      }
    },
    handleSearch () {
      this.$refs.input1.blur()
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        this.$emit('search', this.inputValue)
      }, 200)
    },
    handleClose () {
      this.inputValue = ''
      this.$emit('search', this.inputValue)
    },
    clearValue () {
      this.inputValue = ''
    }
  }
}
</script>

<style lang="less" scoped>
.search-bar {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  margin:.5em .6em;
  background: #Fff;
  .search-input {
    border: 1px solid #fff;
    padding: .6em 1em;
    display: block;
    width: 100%;
    box-shadow: 0;
  }
  .icon-ssousuo, .icon-close {
    color:#ccc;
    position: absolute;
    right: 1em;
    top: .3em;
    background: #fff;
    cursor: pointer;
    display: block;
  }
}
</style>
